package com.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * DruidDataSourceConfig
 */
@Configuration
public class DruidDataSourceConfig {
    //编写方法注入DruidDataSource数据源

    /**
     * 1.默认数据源是如何进行配置的？
     * 在DataSourceAutoConfiguration配置类中
     *
     * @return
     * @ConditionalOnMissingBean({ DataSource.class}) :判断如果容器中有DataSource Bean 就不注入默认的数据源。如果容器中没有DataSource，那就注入默认的数据源
     */
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource dataSource() throws SQLException {
        /**
         * 1.配置了@ConfigurationProperties("spring.datasource")
         * 就可以读取到我们的application.yml配置
         * 2.我们就不需要调用DruidDataSource对象的setXxx,会自动进行关联
         */
        DruidDataSource druidDataSource =
                new DruidDataSource();
        //加入监控功能,加入防火墙监控
        druidDataSource.setFilters("stat,wall");
        return druidDataSource;
    }

    //配置Druid的监控页功能
    @Bean
    public ServletRegistrationBean statViewServlet() {
        //创建statViewServlet
        StatViewServlet statViewServlet =
                new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> servletRegistrationBean =
                new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        //设置init-parameter,设置用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername", "zjb");
        servletRegistrationBean.addInitParameter("loginPassword", "123");
        return servletRegistrationBean;
    }

    //配置WebStatFilter,用于采集web-jdbc关联的监控数据
    @Bean
    public FilterRegistrationBean webStatFilter() {
        //创建WebStatFilter
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> filterRegistrationBean =
                new FilterRegistrationBean<>(webStatFilter);
        //表示对所有的请求都进行监控
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        //排除指定的url
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}
